package com.common;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;

import com.common.logger.AndroidLogAdapter;
import com.common.logger.FormatStrategy;
import com.common.logger.Logger;
import com.common.logger.PrettyFormatStrategy;
import com.common.net.ViseHttp;
import com.common.net.interceptor.HttpLogInterceptor;
import com.squareup.leakcanary.LeakCanary;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class CommonApplication extends Application {

    private static CommonApplication instance;
    public static CommonApplication getInstance() {
        return instance;
    }
    private static Looper mainLooper;//循环队列
    private static Handler handler;//主线程Handler
    private static Thread mainThread;//主线程
    private static long mainThreadId;//主线程id

    @Override

    public void onCreate() {
        super.onCreate();
        instance = this;
        //对全局属性赋值
        mainThread = Thread.currentThread();
        mainThreadId = android.os.Process.myTid();
        handler = new Handler();

        /**
         *日志打印初始化
         */
        //Initialize初始化
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(true)  // (Optional) Whether to show thread info or not. Default true
                .methodCount(2)         // (Optional) How many method line to show. Default 2
                .methodOffset(3)        // (Optional) Skips some method invokes in stack trace. Default 5
//        .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat
                .tag("Staff")   // (Optional) Custom tag for each log. Default PRETTY_LOGGER
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy));
        //todo
        Logger.d("message");
        Logger.w("no thread info and only 1 method");
        Logger.i("no thread info and method info");
        Logger.e("Custom tag for only one use");//错误信息 红色的
        Logger.json("{ \"key\": 3, \"value\": something}");
        Logger.d(Arrays.asList("foo", "bar"));
        Map<String, String> map = new HashMap<>();
        map.put("key", "value");
        map.put("key1", "value2");
        Logger.d(map);

        /**
         *LeakCanary 内存泄漏检测
         */
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);

        /**
         * 网络相关
         */
       /* ViseHttp.init(this);
        ViseHttp.CONFIG()
                //配置请求主机地址
                .baseUrl("http://192.168.1.100/")
                //配置全局请求头
                .globalHeaders(new HashMap<String, String>())
                //配置全局请求参数
                .globalParams(new HashMap<String, String>())
                //配置读取超时时间，单位秒
                .readTimeout(30)
                //配置写入超时时间，单位秒
                .writeTimeout(30)
                //配置连接超时时间，单位秒
                .connectTimeout(30)
                //配置请求失败重试次数
                .retryCount(3)
                //配置请求失败重试间隔时间，单位毫秒
                .retryDelayMillis(1000)
                //配置是否使用cookie
                .setCookie(true)
                //配置自定义cookie
                .apiCookie(new ApiCookie(this))
                //配置是否使用OkHttp的默认缓存
                .setHttpCache(true)
                //配置OkHttp缓存路径
                .setHttpCacheDirectory(new File(ViseHttp.getContext().getCacheDir(), CommonConfig.CACHE_HTTP_DIR))
                //配置自定义OkHttp缓存
                .httpCache(new Cache(new File(ViseHttp.getContext().getCacheDir(), CommonConfig.CACHE_HTTP_DIR), CommonConfig.CACHE_MAX_SIZE))
                //配置自定义离线缓存
                .cacheOffline(new Cache(new File(ViseHttp.getContext().getCacheDir(), CommonConfig.CACHE_HTTP_DIR), CommonConfig.CACHE_MAX_SIZE))
                //配置自定义在线缓存
                .cacheOnline(new Cache(new File(ViseHttp.getContext().getCacheDir(), CommonConfig.CACHE_HTTP_DIR), CommonConfig.CACHE_MAX_SIZE))
                //配置开启Gzip请求方式，需要服务器支持
                .postGzipInterceptor()
                //配置应用级拦截器
                .interceptor(new HttpLogInterceptor()
                        .setLevel(HttpLogInterceptor.Level.BODY))
                //配置网络拦截器
                .networkInterceptor(new NoCacheInterceptor())
                //配置转换工厂
                .converterFactory(GsonConverterFactory.create())
                //配置适配器工厂
                .callAdapterFactory(RxJava2CallAdapterFactory.create())
                //配置请求工厂
                .callFactory(new Call.Factory() {
                    @Override
                    public Call newCall(Request request) {
                        return null;
                    }
                })
                //配置连接池
                .connectionPool(new ConnectionPool())
                //配置主机证书验证
                .hostnameVerifier(new SSLUtil.UnSafeHostnameVerifier("http://192.168.1.100/"))
                //配置SSL证书验证
                .SSLSocketFactory(SSLUtil.getSslSocketFactory(null, null, null))
                //配置主机代理
                .proxy(new Proxy(Proxy.Type.HTTP, new SocketAddress() {}));*/

           /* ViseHttp.init(this);
            ViseHttp.CONFIG()
                    //配置请求主机地址
                    .baseUrl("")
                    .setCookie(false)
                    //配置日志拦截器
                    .interceptor(new HttpLogInterceptor().setLevel(HttpLogInterceptor.Level.BODY));*/
        ViseHttp.init(this);
        ViseHttp.CONFIG()
                //配置请求主机地址
                .baseUrl("http://is.snssdk.com/")
                .setCookie(false)
                //配置日志拦截器
                .interceptor(new HttpLogInterceptor());

    }

    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
    }

    /**
     * 重启当前应用
     */
    public static void restart() {
        Intent intent = getInstance().getPackageManager().getLaunchIntentForPackage(getInstance().getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        getInstance().startActivity(intent);
    }

    public static Thread getMainThread() {
        return mainThread;
    }

    public static void setMainThread(Thread mMainThread) {
        CommonApplication.mainThread = mMainThread;
    }

    public static long getMainThreadId() {
        return mainThreadId;
    }

    public static void setMainThreadId(long mMainThreadId) {
        CommonApplication.mainThreadId = mMainThreadId;
    }

    public static Looper getMainThreadLooper() {
        return mainLooper;
    }

    public static void setMainThreadLooper(Looper mainLooper) {
        CommonApplication.mainLooper = mainLooper;
    }

    public static Handler getMainHandler() {
        return handler;
    }

    public static void setMainHandler(Handler handler) {
        CommonApplication.handler = handler;
    }
}
